package tazadum.engine;

import java.util.concurrent.atomic.AtomicInteger;

public class Interval implements Comparable<Interval> {
	private static AtomicInteger counter = new AtomicInteger(0);

	private final float from;
	private final float to;
	private final int index;

	public Interval(final float from, final float to) {
		this.from = from;
		this.to = to;
		this.index = counter.incrementAndGet();
	}

	public float from() {
		return from;
	}

	public float to() {
		return to;
	}

	public boolean isStarted(final float time) {
		return from <= time;
	}

	public boolean isAfter(final float time) {
		return to < time;
	}

	public float alpha(final float time) {
		if (time <= from) {
			return 0;
		}
		if (time >= to) {
			return 1;
		}

		return (time - from) / (to - from);
	}

	@Override
	public int compareTo(final Interval o) {
		if (from == o.from) {
			if (to == o.to) {
				return index < o.index ? -1 : (index == o.index ? 0 : 1);
			}
			return to < o.to ? -1 : (to == o.to ? 0 : 1);
		}
		return from < o.from ? -1 : (from == o.from ? 0 : 1);
	}

	@Override
	public String toString() {
		return String.format("[%.2f->%.2f]", from, to);
	}

	public float length() {
		return to - from;
	}
}
